<template>
    <div class="address-manage">
      <NavBar>
        <template #default>收货地址</template>
      </NavBar>

      <!-- 地址列表 -->
      <div class="address-list">
        <div
          v-for="address in addressStore.addresses"
          :key="address.addressId"
          class="address-item"
        >
          <div class="address-content">
            <div class="address-header">
              <div class="recipient-info">
                <span class="name">{{ address.receiverName }}</span>
                <span class="phone">{{ address.receiverMobile }}</span>
              </div>
              <div class="default-badge" v-if="address.isDefault">
                <span>默认</span>
              </div>
            </div>

            <div class="address-detail">
              <p>{{ formatAddress(address) }}</p>
            </div>

            <div class="address-actions">
              <el-button
                type="primary"
                link
                @click="editAddress(address)"
              >
                编辑
              </el-button>
              <el-button
                type="primary"
                link
                @click="setDefault(address.addressId)"
                v-if="!address.isDefault"
              >
                设为默认
              </el-button>
              <el-button
                type="danger"
                link
                @click="confirmDelete(address.addressId)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="addressStore.addresses.length === 0" class="empty-state">
          <el-icon class="empty-icon">
            <Location />
          </el-icon>
          <p>暂无收货地址</p>
          <p class="empty-tip">添加收货地址，享受便捷购物体验</p>
        </div>
      </div>

      <!-- 添加地址按钮 -->
      <div class="add-address-btn">
        <el-button type="primary" @click="addNewAddress" class="add-btn">
          <el-icon><Plus /></el-icon>
          添加新地址
        </el-button>
      </div>

      <!-- 地址编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEditing ? '编辑地址' : '添加地址'"
        width="90%"
        class="address-dialog"
      >
        <el-form
          ref="addressFormRef"
          :model="addressForm"
          :rules="addressRules"
          label-width="80px"
          class="address-form"
        >
          <el-form-item label="收货人" prop="receiverName">
            <el-input
              v-model="addressForm.receiverName"
              placeholder="请输入收货人姓名"
              maxlength="50"
            />
          </el-form-item>

          <el-form-item label="手机号" prop="receiverMobile">
            <el-input
              v-model="addressForm.receiverMobile"
              placeholder="请输入手机号"
              maxlength="20"
            />
          </el-form-item>

          <!-- 省市区三级选择框 -->
          <el-form-item label="省份" prop="province">
            <el-select
              v-model="selectedProvince"
              placeholder="请选择省份"
              @change="onProvinceChange"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="province in provinceOptions"
                :key="province.value"
                :label="province.label"
                :value="province.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="城市" prop="city">
            <el-select
              v-model="selectedCity"
              placeholder="请选择城市"
              @change="onCityChange"
              style="width: 100%"
              :disabled="!selectedProvince"
              clearable
            >
              <el-option
                v-for="city in cityOptions"
                :key="city.value"
                :label="city.label"
                :value="city.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="区县" prop="district">
            <el-select
              v-model="selectedDistrict"
              placeholder="请选择区县"
              @change="onDistrictChange"
              style="width: 100%"
              :disabled="!selectedCity"
              clearable
            >
              <el-option
                v-for="district in districtOptions"
                :key="district.value"
                :label="district.label"
                :value="district.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="详细地址" prop="detailAddress">
            <el-input
              v-model="addressForm.detailAddress"
              type="textarea"
              :rows="3"
              placeholder="请输入详细地址（街道、门牌号等）"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item>
            <el-checkbox v-model="addressForm.isDefault">
              设为默认地址
            </el-checkbox>
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="submitAddress"
              :loading="submitLoading"
            >
              保存
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>

  <script setup>
  import { ref, reactive, onMounted, computed } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Plus, Location } from '@element-plus/icons-vue';
  import NavBar from '@/components/common/NavBar.vue';
  import { useAddressStore } from '@/stores/address';
  import { useUserStore } from '@/stores/user';
      import { regionData, CodeToText, TextToCode } from 'element-china-area-data';

  const addressStore = useAddressStore();
  const userStore = useUserStore();

  // 对话框相关
  const dialogVisible = ref(false);
  const isEditing = ref(false);
  const submitLoading = ref(false);
  const addressFormRef = ref(null);

  // 表单数据
  const addressForm = reactive({
    addressId: null,
    userId: null,
    receiverName: '',
    receiverMobile: '',
    province: '',
    city: '',
    district: '',
    detailAddress: '',
    isDefault: 0,
    addressStatus: 1
  });

  // 独立的省市区选择状态
  const selectedProvince = ref('');
  const selectedCity = ref('');
  const selectedDistrict = ref('');

  // 省市区数据选项
  const provinceOptions = computed(() => {
    return regionData.map(province => ({
      value: province.value,
      label: province.label
    }));
  });

  const cityOptions = ref([]);
  const districtOptions = ref([]);



  // 表单验证规则
  const addressRules = {
    receiverName: [
      { required: true, message: '收货人姓名不能为空', trigger: 'blur' },
      { max: 50, message: '收货人姓名长度不能超过50个字符', trigger: 'blur' }
    ],
    receiverMobile: [
      { required: true, message: '收货人手机不能为空', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' },
      { max: 20, message: '收货人手机长度不能超过20个字符', trigger: 'blur' }
    ],
    province: [
      { required: true, message: '请选择省份', trigger: 'change' }
    ],
    city: [
      { required: true, message: '请选择城市', trigger: 'change' }
    ],
    district: [
      { required: true, message: '请选择区县', trigger: 'change' }
    ],
    detailAddress: [
      { required: true, message: '详细地址不能为空', trigger: 'blur' },
      { max: 500, message: '详细地址长度不能超过500个字符', trigger: 'blur' }
    ]
  };

  // 初始化
  onMounted(async () => {
    console.log('地址页面初始化，省市区数据:', regionData.length, '个省份');
    if (userStore.userInfo) {
      await loadAddresses();
    }
  });

// 加载地址列表
const loadAddresses = async () => {
  try {
    // 使用新的初始化方法，优先从本地存储加载
    await addressStore.initializeAddresses();
  } catch (error) {
    ElMessage.error(error.message || '加载地址列表失败');
  }
};

  // 格式化地址显示
    const formatAddress = (address) => {
    return `${address.province}${address.city}${address.district}${address.detailAddress}`;
  };

  // 省份变化处理
  const onProvinceChange = (provinceCode) => {
    console.log('选择省份:', provinceCode);

    // 清空城市和区县
    selectedCity.value = '';
    selectedDistrict.value = '';
    cityOptions.value = [];
    districtOptions.value = [];
    addressForm.city = '';
    addressForm.district = '';

    if (provinceCode) {
      // 找到对应省份的数据
      const province = regionData.find(p => p.value === provinceCode);
      if (province) {
        // 直接使用省份的label作为名称
        addressForm.province = province.label;

        // 加载城市数据
        if (province.children) {
          cityOptions.value = province.children.map(city => ({
            value: city.value,
            label: city.label
          }));
        }
      }
    } else {
      addressForm.province = '';
    }
  };

  // 城市变化处理
  const onCityChange = (cityCode) => {
    console.log('选择城市:', cityCode);

    // 清空区县
    selectedDistrict.value = '';
    districtOptions.value = [];
    addressForm.district = '';

    if (cityCode && selectedProvince.value) {
      // 找到对应省份和城市的数据
      const province = regionData.find(p => p.value === selectedProvince.value);
      if (province && province.children) {
        const city = province.children.find(c => c.value === cityCode);
        if (city) {
          // 直接使用城市的label作为名称
          addressForm.city = city.label;

          // 加载区县数据
          if (city.children) {
            districtOptions.value = city.children.map(district => ({
              value: district.value,
              label: district.label
            }));
          }
        }
      }
    } else {
      addressForm.city = '';
    }
  };

  // 区县变化处理
  const onDistrictChange = (districtCode) => {
    console.log('选择区县:', districtCode);

    if (districtCode && selectedProvince.value && selectedCity.value) {
      // 找到对应的区县数据
      const province = regionData.find(p => p.value === selectedProvince.value);
      if (province && province.children) {
        const city = province.children.find(c => c.value === selectedCity.value);
        if (city && city.children) {
          const district = city.children.find(d => d.value === districtCode);
          if (district) {
            // 直接使用区县的label作为名称
            addressForm.district = district.label;

            console.log('地区选择完成:', {
              province: addressForm.province,
              city: addressForm.city,
              district: addressForm.district
            });
          }
        }
      }
    } else {
      addressForm.district = '';
    }
  };

  // 根据省市区文本获取代码（用于编辑时回显）
  const getRegionCodeByText = (province, city, district) => {
    try {
      if (!province || !city || !district) return { provinceCode: '', cityCode: '', districtCode: '' };

      // 在regionData中查找匹配的省市区
      const foundProvince = regionData.find(p => p.label === province);
      if (!foundProvince) return { provinceCode: '', cityCode: '', districtCode: '' };

      const foundCity = foundProvince.children?.find(c => c.label === city);
      if (!foundCity) return { provinceCode: foundProvince.value, cityCode: '', districtCode: '' };

      const foundDistrict = foundCity.children?.find(d => d.label === district);
      if (!foundDistrict) return { provinceCode: foundProvince.value, cityCode: foundCity.value, districtCode: '' };

      return {
        provinceCode: foundProvince.value,
        cityCode: foundCity.value,
        districtCode: foundDistrict.value
      };
    } catch (error) {
      console.error('获取地区代码失败:', error);
      return { provinceCode: '', cityCode: '', districtCode: '' };
    }
  };

  // 添加新地址
  const addNewAddress = () => {
    resetForm();
    isEditing.value = false;
    dialogVisible.value = true;
    addressForm.userId = userStore.userInfo?.userId;
  };

  // 编辑地址
  const editAddress = (address) => {
    resetForm();
    isEditing.value = true;
    dialogVisible.value = true;

    // 填充表单数据，处理isDefault的转换
    Object.assign(addressForm, {
      ...address,
      isDefault: address.isDefault ? 1 : 0 // 确保isDefault是数字类型
    });

    // 根据省市区文本设置选择器的值
    if (address.province && address.city && address.district) {
      const { provinceCode, cityCode, districtCode } = getRegionCodeByText(address.province, address.city, address.district);

      if (provinceCode) {
        selectedProvince.value = provinceCode;
        onProvinceChange(provinceCode);

        // 需要等待城市选项加载完成后再设置城市
        setTimeout(() => {
          if (cityCode) {
            selectedCity.value = cityCode;
            onCityChange(cityCode);

            // 需要等待区县选项加载完成后再设置区县
            setTimeout(() => {
              if (districtCode) {
                selectedDistrict.value = districtCode;
                onDistrictChange(districtCode);
              }
            }, 100);
          }
        }, 100);
      }
    }

    console.log('编辑地址:', address.province, address.city, address.district);
  };

  // 重置表单
  const resetForm = () => {
    Object.assign(addressForm, {
      addressId: null,
      userId: null,
      receiverName: '',
      receiverMobile: '',
      province: '',
      city: '',
      district: '',
      detailAddress: '',
      isDefault: 0,
      addressStatus: 1
    });

    // 重置选择器状态
    selectedProvince.value = '';
    selectedCity.value = '';
    selectedDistrict.value = '';
    cityOptions.value = [];
    districtOptions.value = [];

    if (addressFormRef.value) {
      addressFormRef.value.clearValidate();
    }
  };

  // 提交地址
  const submitAddress = async () => {
    if (!addressFormRef.value) return;

    try {
      await addressFormRef.value.validate();
      submitLoading.value = true;

      // 准备提交的数据，确保isDefault是数字类型
      const submitData = {
        ...addressForm,
        isDefault: addressForm.isDefault ? 1 : 0
      };

      console.log('提交地址数据:', submitData);

      if (isEditing.value) {
        await addressStore.updateAddress(addressForm.addressId, submitData);
        ElMessage.success('地址更新成功');
      } else {
        await addressStore.addAddress(submitData);
        ElMessage.success('地址添加成功');
      }

      dialogVisible.value = false;
    } catch (error) {
      ElMessage.error(error.message || '操作失败');
    } finally {
      submitLoading.value = false;
    }
  };

  // 设置默认地址
  const setDefault = async (addressId) => {
    try {
      await addressStore.setDefaultAddress(addressId);
      ElMessage.success('默认地址设置成功');
    } catch (error) {
      ElMessage.error(error.message || '设置默认地址失败');
    }
  };

  // 确认删除地址
  const confirmDelete = async (addressId) => {
    try {
      await ElMessageBox.confirm(
        '确定要删除这个地址吗？',
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      );

      await addressStore.deleteAddress(addressId);
      ElMessage.success('地址删除成功');
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error(error.message || '删除地址失败');
      }
    }
  };
  </script>

  <style scoped>
  .address-manage {
    background-color: #f5f5f5;
    min-height: 100vh;
    padding-bottom: 120px; /* 增加底部内边距，为固定按钮留出空间 */
    position: relative;
  }

  /* 地址列表 */
  .address-list {
    padding: 10px;
    margin-bottom: 20px; /* 为底部按钮留出空间 */
  }

  .address-item {
    background-color: #fff;
    border-radius: 8px;
    margin-bottom: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  }

  .address-content {
    padding: 15px;
  }

  .address-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }

  .recipient-info {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .recipient-info .name {
    font-size: 16px;
    font-weight: 500;
    color: #333;
  }

  .recipient-info .phone {
    font-size: 14px;
    color: #666;
  }

  .default-badge {
    background-color: #ff5000;
    color: #fff;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
  }

  .address-detail {
    margin-bottom: 15px;
  }

  .address-detail p {
    margin: 0;
    font-size: 14px;
    color: #666;
    line-height: 1.5;
  }

  .address-actions {
    display: flex;
    gap: 15px;
    padding-top: 10px;
    border-top: 1px solid #f0f0f0;
  }

  /* 空状态 */
  .empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #999;
  }

  .empty-icon {
    font-size: 48px;
    margin-bottom: 15px;
    color: #ddd;
  }

  .empty-state p {
    margin: 5px 0;
    font-size: 16px;
  }

  .empty-tip {
    font-size: 14px !important;
    color: #ccc !important;
  }

  /* 添加地址按钮 - 优化后的样式 */
  .add-address-btn {
    position: fixed;
    bottom: 80px; /* 增加底部距离，避免被底部导航栏遮挡 */
    left: 50%;
    transform: translateX(-50%);
    z-index: 1000; /* 提高层级 */
    width: 100%;
    max-width: 400px; /* 限制最大宽度 */
    padding: 0 20px;
    box-sizing: border-box;
  }

  .add-btn {
    width: 100%;
    height: 48px; /* 增加按钮高度 */
    border-radius: 24px;
    box-shadow: 0 4px 12px rgba(255, 80, 0, 0.4); /* 增强阴影效果 */
    font-size: 16px;
    font-weight: 500;
    transition: all 0.3s ease;
  }

  .add-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(255, 80, 0, 0.5);
  }

  .add-btn .el-icon {
    margin-right: 8px;
    font-size: 18px;
  }

  /* 对话框样式 */
  :deep(.address-dialog) {
    margin-top: 5vh;
  }

  :deep(.address-dialog .el-dialog__body) {
    padding: 20px;
  }

  .address-form {
    padding: 0 10px;
  }

  :deep(.address-form .el-form-item) {
    margin-bottom: 20px;
  }

  :deep(.address-form .el-input__wrapper) {
    border-radius: 6px;
  }

  :deep(.address-form .el-select) {
    width: 100%;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  /* 响应式调整 */
  @media (max-width: 768px) {
    .address-manage {
      padding-bottom: 100px; /* 移动端减少底部内边距 */
    }

    .address-item {
      margin-bottom: 8px;
    }

    .address-content {
      padding: 12px;
    }

    .recipient-info {
      flex-direction: column;
      align-items: flex-start;
      gap: 5px;
    }

    .address-actions {
      gap: 10px;
    }

    .add-address-btn {
      bottom: 70px; /* 移动端调整底部距离 */
      padding: 0 15px;
    }

    .add-btn {
      height: 44px;
      font-size: 15px;
    }

    :deep(.address-dialog) {
      margin: 0;
      width: 95% !important;
    }
  }

  /* 针对不同屏幕高度的优化 */
  @media (max-height: 600px) {
    .add-address-btn {
      bottom: 60px; /* 小屏幕设备减少底部距离 */
    }
  }

  /* 确保按钮在安全区域内 */
  @supports (padding-bottom: env(safe-area-inset-bottom)) {
    .add-address-btn {
      bottom: calc(80px + env(safe-area-inset-bottom));
    }

    @media (max-width: 768px) {
      .add-address-btn {
        bottom: calc(70px + env(safe-area-inset-bottom));
      }
    }
  }

  /* 移动端对话框优化 */
  @media (max-width: 768px) {
    :deep(.address-dialog) {
      margin: 0 !important;
      width: 100% !important;
      height: 100vh !important;
      max-height: 100vh !important;
      border-radius: 0 !important;
      display: flex;
      flex-direction: column;
    }

    :deep(.address-dialog .el-dialog__header) {
      padding: 15px 20px;
      border-bottom: 1px solid #f0f0f0;
      flex-shrink: 0;
    }

    :deep(.address-dialog .el-dialog__body) {
      flex: 1;
      overflow-y: auto;
      padding: 20px;
    }

    :deep(.address-dialog .el-dialog__footer) {
      padding: 15px 20px;
      border-top: 1px solid #f0f0f0;
      flex-shrink: 0;
    }
  }
  </style>